package top.lyunz.fangkeji.controller.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.EncodeException;

import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import net.coobird.thumbnailator.Thumbnails;
import top.lyunz.fangkeji.service.AttendanceConfigService;
import top.lyunz.fangkeji.service.AttendanceRecordService;
import top.lyunz.fangkeji.service.TravelRecordsService;
import top.lyunz.fangkeji.service.companyService;
import top.lyunz.fangkeji.service.equipmentService;
import top.lyunz.fangkeji.service.fuserService;
import top.lyunz.fangkeji.tools.ExcelUtils;
import top.lyunz.fangkeji.tools.SimpleResult;
import top.lyunz.fangkeji.tools.WanNianLi;
import top.lyunz.fangkeji.tools.baiduyun;
import top.lyunz.fangkeji.tools.delFile;
import top.lyunz.fangkeji.tools.img;
import top.lyunz.fangkeji.tools.sms;
import top.lyunz.fangkeji.webSocketSerevice.WebSocketServer;
import top.lyunz.fangkeji.bean.*;

@Controller
@RequestMapping("/web")
public class web {
	public static String imgurlpath = "c:/img/";
	@Resource
	private fuserService fuserService;
	@Resource
	private companyService companyService;

	/**
	 * 主管理员注册
	 * 
	 * @param registeruser
	 * @param response
	 * @param session
	 * @param model
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/userregister")
	public String userregister(registeruser registeruser, HttpServletResponse response, HttpSession session,
			Model model) throws IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = null;
		String uName = registeruser.getuName();
		String uPwd = registeruser.getuPwd();
		String uTel = registeruser.getuTel();
		MultipartFile file = registeruser.getuImg();
		String originalFilename = file.getOriginalFilename();
		String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
		img img = new img();
		String timeString = System.currentTimeMillis() + "";
		String Img = timeString + prefix;
		String newImg = timeString + "-thumbnail" + prefix;
		img.uploadingImg(file, Img);
		Thumbnails.of(imgurlpath + Img).scale(0.5f).outputQuality(0.5f).toFile(imgurlpath + newImg);
		delFile delFile = new delFile();
		delFile.del(imgurlpath, Img);
		Fuser fuser = new Fuser(null, uName, uPwd, uTel, newImg, 1, 0, 0, 0, null);
		baiduyun baiduyun = new baiduyun();
		Integer baiduyunAPI = baiduyun.baiduyunAPI(imgurlpath + newImg);
		writer = response.getWriter();
		String cName = registeruser.getcName();
		System.currentTimeMillis();
		String cAddress = registeruser.getcAddress();
		Company company = new Company(null, cName, cAddress, "company.jpg", 0, timeString, 0, null);
		if (baiduyunAPI == null) {
			writer.print(
					"<script type='text/javascript'>alert('人脸头像没有检测到人脸');location.href='/redirect/toregisteruser';</script>");
			writer.flush();
			writer.close();
		} else {
			if (baiduyunAPI != 1) {
				delFile.del(imgurlpath, newImg);
				writer.print(
						"<script type='text/javascript'>alert('人脸头像检测到多张人脸');location.href='/redirect/toregisteruser';</script>");
			} else {
				List<Company> companiesByCname = companyService.getCompaniesByCname(cName);
				int companyAdd = 0;
				if (companiesByCname.size()==0) {
					companyService.companyAdd(company);
				} else{
					companyAdd = 1;
					timeString = companiesByCname.get(0).getcIdentity();
				
				}
				if (companyAdd > 0) {
					Company selcompany = companyService.getCompanyBycIdentity(timeString);
					if (companiesByCname != null) {
						companyService.updCompany(
								new Company(selcompany.getcId(), null, null, null, 0, null, selcompany.getcId(), null));
					}
					List<Fuser> byuTel = fuserService.getByuTel(uTel);
					boolean isregister = false;
					for (Fuser user : byuTel) {
						if (user.getcId() == selcompany.getcId()) {
							isregister = true;
						}
					}
					if (isregister == false) {
						fuser.setcId(selcompany.getcId());
						int isfuseradd = fuserService.fuserAdd(fuser);
						if (isfuseradd > 0) {
							Fuser uFuser = fuserService.getFuserByCidAndUtel(new Fuser(null, null, null, uTel, null,
									null, null, selcompany.getcId(), null, null));
							fuser.setParentLevel(uFuser.getuId());
							fuserService.updateFuser(uFuser);
							fuserService
									.updbByuTel(new Fuser(null, null, uPwd, uTel, null, null, null, null, null, null));
							return "page/login";
						} else {
							companyService.delByCid(selcompany.getcId());
							writer.print(
									"<script type='text/javascript'>alert('注册失败');location.href='/redirect/toregisteruser';</script>");
							writer.flush();
							writer.close();
						}
					} else {
						writer.print(
								"<script type='text/javascript'>alert('注册失败');location.href='/redirect/toregisteruser';</script>");
						writer.flush();
						writer.close();
					}
				}
			}
		}

		return "page/login";
	}

	/**
	 * 注册获取手机验证码
	 * 
	 * @param tel
	 * @return
	 */
	@RequestMapping("/verificationCode/{tel}")
	public @ResponseBody SimpleResult verificationCode(@PathVariable("tel") String tel) {

		SimpleResult result;

		result = new SimpleResult(tel);
		// sms s=new sms();
		// String mobileQuery = s.mobileQuery(tel);

		return result;
	}

	/**
	 * 忘记密码获取手机验证码
	 * 
	 * @param tel
	 * @return
	 */
	@RequestMapping("/updpwdverificationCode/{tel}")
	public @ResponseBody SimpleResult updpwdverificationCode(@PathVariable("tel") String tel) {

		SimpleResult result;
		// sms s=new sms();
		// String mobileQuery = s.mobileQuery(tel);
		result = new SimpleResult(tel);
		return result;
	}

	/**
	 * 登录
	 * 
	 * @param fuser
	 * @param response
	 * @param session
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/dologin")
	public String dologin(Fuser fuser, HttpServletResponse response, HttpSession session, Model model)
			throws IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		List<Fuser> user = fuserService.getFuserGetbyTelAndUpwd(fuser);

		if (user.size() == 0) {
			writer.print(
					"<script type='text/javascript'>alert('手机号码或密码错误!');location.href='/redirect/tologin';</script>");
			writer.flush();
			writer.close();
			return null;
		} else if (user.size() == 1) {
			session.setAttribute("user", user.get(0));
			return "redirect:/redirect/toindex";
		} else if (user.size() > 1) {
			List<loginToChoose> loginToChoose = new ArrayList<loginToChoose>();
			for (Fuser uFuser : user) {
				Company companyByCid = companyService.getCompanyByCid(uFuser.getcId());
				loginToChoose.add(new loginToChoose(uFuser.getuId(), companyByCid.getcName()));
			}
			model.addAttribute("loginToChoose", loginToChoose);
			return "page/loginToChoose";
		} else {
			return null;
		}

	}

	@RequestMapping("/dologinToChoose")
	public String dologinToChoose(loginToChoose choose, HttpSession session) {
		int uid = choose.getUid();
		Fuser user = fuserService.getFuserByuId(uid);
		session.setAttribute("user", user);
		return "redirect:/redirect/toindex";
	}

	/**
	 * 忘记密码
	 * 
	 * @param fuser
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/doupdpwd")
	public String doupdpwd(Fuser fuser, HttpServletResponse response, Model model) throws Exception {
		response.setContentType("text/html;charset=utf-8");
		int is = fuserService.updbByuTel(fuser);
		PrintWriter writer = response.getWriter();
		if (is < 1) {
			writer.print("<script type='text/javascript'>alert('修改失败!');location.href='/redirect/tologin';</script>");
			writer.flush();
			writer.close();
		}
		model.addAttribute("fuser", fuser);

		return "page/login";
	}

	@Resource
	private equipmentService equipmentService;

	/**
	 * 设备分页查询
	 * 
	 * @param cid
	 * @param page
	 * @return
	 */
	@RequestMapping("/getPageEquipments/{cid}/{page}")
	public @ResponseBody SimpleResult getPageEquipments(@PathVariable("cid") int cid, @PathVariable("page") int page,
			HttpSession session) {
		Fuser user = (Fuser) session.getAttribute("user");
		if (user.getuIdentity() == 1) {
			List<Equipment> arr = equipmentService.getAllEquipments(cid);
			int size = arr.size();
			int pageindex = 0;
			int pagemax;
			if (size % 30 == 0) {
				pagemax = size / 30;
			} else {
				pagemax = size / 30 + 1;
			}
			if (page > 1)
				pageindex = (page - 1) * 30;
			List<Equipment> pagearr = equipmentService.getByPageEquipments(new pageselect(pageindex, 30, null, cid));
			return new SimpleResult(pagearr, pagemax);
		} else {
			Company companyByCid = companyService.getCompanyByCid(cid);
			String geteSn = companyByCid.geteSn();
			List<Equipment> equarr = new ArrayList<Equipment>();
			if (geteSn != null && !geteSn.equals("")) {
				if (geteSn.indexOf("-") != -1) {
					String[] esnarr = geteSn.split("-");
					for (int i = 0; i < esnarr.length; i++) {
						equarr.add(equipmentService.getEquipmentBySn(esnarr[i]));
					}
				} else {
					equarr.add(equipmentService.getEquipmentBySn(geteSn));
				}
			}
			int size = equarr.size();
			int pageindex = 0;
			int pagemax;
			if (size % 30 == 0) {
				pagemax = size / 30;
			} else {
				pagemax = size / 30 + 1;
			}
			if (page > 1)
				pageindex = (page - 1) * 30;
			int count = 0;
			List<Equipment> arr = new ArrayList<Equipment>();
			for (int i = 0; i < equarr.size(); i++) {
				if (i == pageindex || i > pageindex) {
					if (count < 30) {
						arr.add(equarr.get(i));
						count++;
					}
				}
			}
			return new SimpleResult(arr, pagemax);
		}
	}

	/**
	 * 添加设备
	 * 
	 * @param equipment
	 * @param response
	 * @param session
	 * @return
	 * @throws IOException
	 * @throws EncodeException
	 */
	@RequestMapping("/addEquipments")
	public String addEquipments(Equipment equipment, HttpServletResponse response, HttpSession session)
			throws IOException, EncodeException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		Equipment obj = equipmentService.getEquipmentBySn(equipment.getsN());
		Fuser user = (Fuser) session.getAttribute("user");
		if (obj == null) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
			String date = df.format(new Date());
			String sN = equipment.getsN();
			String eName = equipment.geteName();
			String eLocation = equipment.geteLocation();
			Equipment equ = new Equipment(null, eName, eLocation, date, null, sN, user.getcId(), 0, 0, 0, 0, 0, 0);
			int isadd = equipmentService.equipmentAdd(equ);
			if (isadd > 0) {
				user.setuStatus(1);
				Fuser fuserByuId = fuserService.getFuserByuId(user.getuId());
				String geteSn = fuserByuId.geteSn();
				geteSn = "-" + equipment.getsN();
				fuserByuId.seteSn(geteSn);
				fuserService.updateFuser(fuserByuId);
				String str = "{typr:'adduser','uId':" + fuserByuId.getuId() + ",'uName':" + fuserByuId.getuName()
						+ ",'uImg:'" + fuserByuId.getuImg() + "}";
				WebSocketServer.sendInfo(str, equipment.getsN());
				Equipment eq = equipmentService.getEquipmentBySn(equipment.getsN());
				user.seteSn(geteSn + "-" + eq.getsN());
				fuserService.updateFuser(user);
				return "page/equipmentManagement/equipment_list";
			} else {
				writer.print(
						"<script type='text/javascript'>alert('设备添加失败!');location.href='/redirect/toequipmentadd';</script>");
				writer.flush();
				writer.close();
			}
		} else {
			if (obj.getcId() == user.getcId()) {
				equipmentService.updEquipmentByeId(new Equipment(obj.geteId(), null, null, null, null, null, null, null,
						null, null, null, null, null));
				return "page/equipmentManagement/equipment_list";
			}
			writer.print(
					"<script type='text/javascript'>alert('设备已被激活!');location.href='/redirect/togetPageEquipments';</script>");
			writer.flush();
			writer.close();
		}

		return null;

	}

	/**
	 * 根据设备ID删除设备
	 * 
	 * @param eid
	 * @return
	 */
	@RequestMapping("/delEquipments/{eid}")
	public @ResponseBody SimpleResult delEquipments(@PathVariable("eid") int eid, HttpSession session) {

		Equipment equipmentByeId = equipmentService.getEquipmentByeId(eid);
		String sN = equipmentByeId.getsN();
		List<Fuser> getlikeeidList = fuserService.getlikeeidList(sN);
		int delEquipments = equipmentService.delEquipments(eid);
		List<Company> allAuthorizationCompanyByeSn = companyService.getAllAuthorizationCompanyByeSn(sN);
		for (Company company : allAuthorizationCompanyByeSn) {
			String geteSn = company.geteSn();
			String eString = "";
			if (geteSn.indexOf("-") != -1) {
				String[] split = geteSn.split("-");

				if (split.length == 2) {
					for (int i = 0; i < split.length; i++) {
						if (split[i] != sN) {
							eString += split[i];
						}
					}
				} else {
					for (int i = 0; i < split.length; i++) {
						if (i == split.length - 1) {
							eString += split[i];
						} else {
							eString = eString + split[i] + "-";
						}
					}
				}
			}
			company.seteSn(eString);
		}
		if (delEquipments > 0) {

			for (Fuser fuser : getlikeeidList) {

				String usereSN = fuser.geteSn();
				if (usereSN != null && !usereSN.equals("")) {
					if (usereSN.indexOf("-") != -1) {
						String[] esnarr = usereSN.split("-");
						String esN = "";
						for (int i = 0; i < esnarr.length; i++) {

							if (i != esnarr.length - 1 && !esnarr[i].equals(sN)) {
								if (esN.equals("")) {
									esN += esnarr[i];
								} else {
									esN += "-" + esnarr[i];
								}
							}
						}
						fuserService.updateFuser(
								new Fuser(fuser.getuId(), null, null, null, null, null, null, null, null, esN));
					} else {
						fuserService.updateFuser(
								new Fuser(fuser.getuId(), null, null, null, null, null, null, null, null, ""));
					}
				}
			}

		}
		return new SimpleResult(delEquipments > 0 ? true : false);

	}

	/**
	 * 根据设备ID查询单个设备
	 * 
	 * @param eid
	 * @param model
	 * @return
	 */
	@RequestMapping("/toupdEquipments/{eid}")
	public @ResponseBody SimpleResult toupdEquipments(@PathVariable("eid") int eid, Model model) {
		return new SimpleResult(equipmentService.getEquipmentByeId(eid));

	}

	/**
	 * 修改单个设备
	 * 
	 * @param equipment
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/doupdEquipments")
	public String doupdEquipments(Equipment equipment, HttpServletResponse response) throws IOException {
		int is = equipmentService.updEquipmentByeId(equipment);
		if (is > 0) {
			return "page/equipmentManagement/equipment_list";
		} else {
			PrintWriter writer = response.getWriter();
			writer.print(
					"<script type='text/javascript'>alert('修改设备信息失败!');location.href='/page/equipmentManagement/equipment_list';</script>");
			writer.flush();
			writer.close();
		}
		return null;

	}

	/**
	 * 公司分页查询
	 * 
	 * @param page
	 * @param session
	 * @return
	 */
	@RequestMapping("/getPageCompany/{page}")
	public @ResponseBody SimpleResult getPageCompany(@PathVariable("page") int page, HttpSession session) {
		Fuser user = (Fuser) session.getAttribute("user");
		List<Company> arr = new ArrayList<Company>();
		List<Company> comarr = new ArrayList<Company>();
		if (user.getuIdentity() == 1) {
			arr = companyService.getCompaniesByParentLevel(user.getcId());
		} else if (user.getuIdentity() == 2) {
			arr.add(companyService.getCompanyByCid(user.getcId()));
		}
		int size = arr.size();
		int pageindex = 0;
		int pagemax;
		if (size % 20 == 0) {
			pagemax = size / 20;
		} else {
			pagemax = size / 20 + 1;
		}
		if (page > 1)
			pageindex = (page - 1) * 20;
		if (user.getuIdentity() == 1) {
			comarr = companyService.getCompaniesBypage(new pageselect(pageindex, 20, null, user.getcId()));
			return new SimpleResult(comarr, pagemax);
		} else if (user.getuIdentity() == 2) {
			return new SimpleResult(arr, pagemax);
		} else {
			return null;
		}

	}

	/**
	 * 冻结公司
	 * 
	 * @param cid
	 * @return
	 * @throws EncodeException
	 * @throws IOException
	 */
	@RequestMapping("/pauseCompany/{cid}")
	public @ResponseBody SimpleResult pauseCompany(@PathVariable("cid") int cid) throws IOException, EncodeException {
		int is = companyService.updCompany(new Company(cid, null, null, null, 1, null, null, null));
		if (is > 0) {
			fuserService.batchUpdEidByCid(new Fuser(null, null, null, null, null, null, 2, cid, null, null));
			List<Fuser> fusersAllByCid = fuserService.getFusersAllByCid(cid);
			for (Fuser fuser : fusersAllByCid) {
				Integer getuId = fuser.getuId();
				String geteSn = fuser.geteSn();
				String getuName = fuser.getuName();
				String getuImg = fuser.getuImg();
				if (geteSn != null && geteSn != "") {
					if (geteSn.indexOf("-") != -1) {
						String[] st = geteSn.split("-");
						for (int i = 0; i < st.length; i++) {
							String str = "{typr:'deluser','uId':" + getuId+"}";
							WebSocketServer.sendInfo(str, st[i]);
						}
					} else {
						String str = "{typr:'deluser','uId':" + getuId 
								+ "}";
						WebSocketServer.sendInfo(str, geteSn);
					}
				}

			}

		}
		return new SimpleResult(is > 0 ? true : false);
	}

	/**
	 * 恢复公司状态
	 * 
	 * @param cid
	 * @return
	 * @throws EncodeException
	 * @throws IOException
	 */
	@RequestMapping("/recoverCompany/{cid}")
	public @ResponseBody SimpleResult recoverCompany(@PathVariable("cid") int cid) throws IOException, EncodeException {
		int is = companyService.updCompany(new Company(cid, null, null, null, 0, null, null, null));
		if (is > 0) {
			Company companyByCid = companyService.getCompanyByCid(cid);
			fuserService.batchUpdEidByCid(
					new Fuser(null, null, null, null, null, null, 1, cid, null, companyByCid.geteSn()));
			if (companyByCid.geteSn() != null && !companyByCid.geteSn().equals("")) {
				if (companyByCid.geteSn().indexOf("-") != -1) {
					String[] st = companyByCid.geteSn().split("-");
					for (String string : st) {
						equipmentService.updEquipmentByesN(
								new Equipment(null, null, null, null, null, string, null, 0, 0, 0, 1, 0, 0));
					}
				}
			}

			List<Fuser> fusersAllByCid = fuserService.getFusersAllByCid(cid);
			for (Fuser fuser : fusersAllByCid) {
				Integer getuId = fuser.getuId();
				String geteSn = fuser.geteSn();
				String getuName = fuser.getuName();
				String getuImg = fuser.getuImg();
				if (geteSn != null || geteSn != "") {
					if (geteSn.indexOf("-") != -1) {
						String[] st = geteSn.split("-");
						for (int i = 0; i < st.length; i++) {
							String str = "{typr:'adduser','uId':" + getuId + ",'uName':" + getuName + ",'uImg':"
									+ getuImg + "}";
							WebSocketServer.sendInfo(str, st[i]);
						}
					} else {
						String str = "{typr:'adduser','uId':" + getuId + ",'uName':" + getuName + ",'uImg':" + getuImg
								+ "}";
						WebSocketServer.sendInfo(str, geteSn);
					}
				}
			}
		}
		return new SimpleResult(is > 0 ? true : false);
	}

	/**
	 * 添加公司
	 * 
	 * @param companyAdd
	 * @param session
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/companyAdd")
	public String company_add(companyAdd companyAdd, HttpSession session, HttpServletResponse response)
			throws IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		MultipartFile cImg = companyAdd.getcImg();
		String cName = companyAdd.getcName();
		String cAddress = companyAdd.getcAddress();
		String[] geteId = companyAdd.geteSn();
		String eId = "";
		if (geteId != null && !geteId.equals("")) {
			for (int i = 0; i < geteId.length; i++) {
				if (i == geteId.length - 1) {
					eId += geteId[i];
				} else {
					eId = eId + geteId[i] + "-";
				}
			}
		}
		img img = new img();
		String newImg;
		delFile delFile = new delFile();
		String timeString = System.currentTimeMillis() + "";
		if (!cImg.isEmpty()) {
			String originalFilename = cImg.getOriginalFilename();
			String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
			String Img = timeString + cName + prefix;
			newImg = timeString + "-thumbnail" + prefix;
			img.uploadingImg(cImg, Img);
			Thumbnails.of(imgurlpath + Img).scale(0.5f).outputQuality(0.5f).toFile(imgurlpath + newImg);
			delFile.del(imgurlpath, Img);
		} else {
			newImg = "company.jpg";
		}
		Fuser user = (Fuser) session.getAttribute("user");
		List<Company> companiesByCname = companyService.getCompaniesByCname(cName);
		if (companiesByCname != null) {
			int is = companyService
					.companyAdd(new Company(null, cName, cAddress, newImg, 0, timeString, user.getcId(), eId));
			if (is > 0) {
				return "page/staffManagement/user_list";
			} else {
				delFile.del(imgurlpath, newImg);
				writer.print(
						"<script type='text/javascript'>alert('添加公司失败!');location.href='/page/companyManagement/company_list';</script>");
				writer.flush();
				writer.close();
				return null;
			}
		} else {
			delFile.del(imgurlpath, newImg);
			writer.print(
					"<script type='text/javascript'>alert('该公司名已经存在!');location.href='/page/companyManagement/company_list';</script>");
			writer.flush();
			writer.close();
			return null;
		}

	}

	/**
	 * 查询单个公司
	 * 
	 * @param cid
	 * @param model
	 * @return
	 */
	@RequestMapping("/companytoUpd/{cid}")
	public @ResponseBody SimpleResult companyUpd(@PathVariable("cid") int cid, Model model) {
		return new SimpleResult(companyService.getCompanyByCid(cid));
	}

	/**
	 * 公司修改
	 * 
	 * @param companyAdd
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws EncodeException
	 */
	@RequestMapping("/companytdoUpd")
	public String companytdoUpd(companyAdd companyAdd, HttpServletResponse response)
			throws IOException, EncodeException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		MultipartFile cImg = companyAdd.getcImg();
		String cName = companyAdd.getcName();
		String cAddress = companyAdd.getcAddress();
		String[] geteId = companyAdd.geteSn();

		int cid = companyAdd.getcId();
		Company companyByCid = companyService.getCompanyByCid(cid);
		String geteSn = companyByCid.geteSn();
		String eId = "";
		if (geteId != null) {
			for (int i = 0; i < geteId.length; i++) {
				if (i == geteId.length - 1) {
					eId += geteId[i];
				} else {
					eId = eId + geteId[i] + "-";
				}
			}
		}
		img img = new img();
		String newImg;
		delFile delFile = new delFile();
		String timeString = System.currentTimeMillis() + "";
		if (!cImg.isEmpty()) {
			String originalFilename = cImg.getOriginalFilename();
			String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
			String Img = timeString + prefix;
			newImg = timeString + "-thumbnail" + prefix;
			img.uploadingImg(cImg, Img);
			Thumbnails.of(imgurlpath + Img).scale(0.5f).outputQuality(0.5f).toFile(imgurlpath + newImg);
			delFile.del(imgurlpath, Img);
			String getcImg = companyByCid.getcImg();
			delFile.del(imgurlpath, getcImg);
		} else {
			newImg = null;
		}
		List<Company> companiesByCname = companyService.getCompaniesByCname(cName);
		if (companiesByCname != null) {
			int is = companyService.updCompany(new Company(cid, cName, cAddress, newImg, null, null, null, eId));
			fuserService.batchUpdEidByCid(new Fuser(null, null, null, null, null, null, null, cid, null, eId));
			if (is > 0) {
				if (geteSn != null || geteSn != "") {
					List<Fuser> fusersAllByCid = fuserService.getFusersAllByCid(cid);
					for (Fuser fuser : fusersAllByCid) {
						Integer getuId = fuser.getuId();
						String getuName = fuser.getuName();
						String getuImg = fuser.getuImg();
						if (geteSn != null || geteSn != "") {
							if (geteSn.indexOf("-") != -1) {
								String[] st = geteSn.split("-");
								for (int i = 0; i < st.length; i++) {
									String str = "{typr:'deluser','uId':" + getuId + "}";
									WebSocketServer.sendInfo(str, st[i]);
								}
							} else {
								String str = "{typr:'deluser','uId':" + getuId + "}";
								WebSocketServer.sendInfo(str, geteSn);
							}
						}
						if (eId != null || eId != "") {
							if (geteSn.indexOf("-") != -1) {
								String[] st = geteSn.split("-");
								for (int i = 0; i < st.length; i++) {
									String str = "{typr:'adduser','uId':" + getuId + ",'uName':" + getuName + ",'uImg':"
											+ getuImg + "}";
									WebSocketServer.sendInfo(str, st[i]);
								}
							} else {
								String str = "{typr:'adduser','uId':" + getuId + ",'uName':" + getuName + ",'uImg':"
										+ getuImg + "}";
								WebSocketServer.sendInfo(str, geteSn);
							}
						}
					}
				}
				return "page/companyManagement/company_list";
			} else {
				delFile.del(imgurlpath, newImg);
				writer.print(
						"<script type='text/javascript'>alert(修改公司失败!');location.href='/page/companyManagement/company_list';</script>");
				writer.flush();
				writer.close();
				return null;
			}
		} else {
			if (!cImg.isEmpty()) {
				delFile.del(imgurlpath, newImg);
			}
			writer.print(
					"<script type='text/javascript'>alert(修改公司失败!');location.href='/page/companyManagement/company_list';</script>");
			writer.flush();
			writer.close();
			return null;
		}

	}

	/**
	 * 分页查询员工
	 * 
	 * @param page
	 * @param session
	 * @return
	 */
	@RequestMapping("/getPageuser/{page}")
	public @ResponseBody SimpleResult getPageuser(@PathVariable("page") int page, HttpSession session) {
		Fuser user = (Fuser) session.getAttribute("user");
		List<Fuser> arr = new ArrayList<Fuser>();
		List<Fuser> fusersAllBy = fuserService.getFusersAllByCid(user.getcId());
		int size = fusersAllBy.size();
		int pageindex = 0;
		int pagemax;
		if (size % 20 == 0) {
			pagemax = size / 20;
		} else {
			pagemax = size / 20 + 1;
		}
		if (page > 1)
			pageindex = (page - 1) * 20;
		arr = fuserService.getFuserBypage(new pageselect(pageindex, 20, null, user.getcId()));
		return new SimpleResult(arr, pagemax);
	}

	/**
	 * 分页查询员工到前台页面
	 * 
	 * @param page
	 * @param session
	 * @return
	 */
	@RequestMapping("/getPageusertoapge/{cId}")
	public String getPageusertoapge(@PathVariable("cId") int cId, HttpSession session, Model model) {
		List<Fuser> arr = new ArrayList<Fuser>();
		List<Fuser> fusersAllBy = fuserService.getFusersAllByCid(cId);
		int size = fusersAllBy.size();
		int pageindex = 0;
		int pagemax;
		if (size % 20 == 0) {
			pagemax = size / 20;
		} else {
			pagemax = size / 20 + 1;
		}
		int page = 1;
		if (page > 1)
			pageindex = (page - 1) * 20;
		arr = fuserService.getFuserBypage(new pageselect(pageindex, 20, null, cId));
		model.addAttribute("users", arr);
		model.addAttribute("cId", cId);
		model.addAttribute("pagemax", pagemax);
		return "page/staffManagement/user_list";
	}

	/**
	 * 删除员工
	 * 
	 * @param uid
	 * @return
	 * @throws IOException
	 * @throws EncodeException
	 */
	@RequestMapping("/deluser/{uid}")
	public @ResponseBody SimpleResult deluser(@PathVariable int uid) throws IOException, EncodeException {
		Fuser fuserByuId = fuserService.getFuserByuId(uid);

		int delFuser = fuserService.delFuser(uid);
		if (delFuser > 0) {
			if (fuserByuId.geteSn() != null && fuserByuId.geteSn() != "") {
				if (fuserByuId.geteSn().indexOf("-") != -1) {
					String[] sts = fuserByuId.geteSn().split("-");
					for (int i = 0; i < sts.length; i++) {
						String str = "{typr:'deluser','uId':" + fuserByuId.getuId() + "}";
						WebSocketServer.sendInfo(str, sts[i]);
					}
				} else {
					String str = "{typr:'deluser','uId':" + fuserByuId.getuId() + "}";
					WebSocketServer.sendInfo(str, fuserByuId.geteSn());
				}
			}
		}
		return new SimpleResult(delFuser > 0 ? true : false);
	}

	/**
	 * 权限转让
	 * 
	 * @param uid
	 * @param session
	 * @return
	 */
	@RequestMapping("permissionToExchange/{uid}")
	public @ResponseBody SimpleResult permissionToExchange(@PathVariable("uid") int uid, HttpSession session) {
		Fuser user = (Fuser) session.getAttribute("user");
		user.setuIdentity(2);
		boolean is = false;
		Fuser fuserByuId = fuserService.getFuserByuId(uid);
		fuserByuId.setuIdentity(1);
		if (fuserService.updateFuser(user) > 0 && fuserService.updateFuser(fuserByuId) > 0) {
			is = true;
		}
		return new SimpleResult(is);
	}

	/**
	 * 添加员工
	 * 
	 * @param userAdd
	 * @param response
	 * @param session
	 * @throws IOException
	 * @throws EncodeException
	 */
	@RequestMapping("/douserAdd/{cid}")
	public void douserAdd(@PathVariable("cid") Integer cId, userAdd userAdd, HttpServletResponse response,
			HttpSession session) throws IOException, EncodeException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		MultipartFile uImg = userAdd.getuImg();
		String uName = userAdd.getuName();
		String uTel = userAdd.getuTel();
		String[] geteId = userAdd.geteSn();
		String eId = "";
		if (geteId != null) {
			for (int i = 0; i < geteId.length; i++) {
				if (i == geteId.length - 1) {
					eId += geteId[i];
				} else {
					eId = eId + geteId[i] + "-";
				}
			}
		}
		img img = new img();
		String newImg;
		delFile delFile = new delFile();
		String timeString = System.currentTimeMillis() + "";

		String originalFilename = uImg.getOriginalFilename();
		String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
		String Img = timeString + prefix;
		newImg = timeString + "-thumbnail" + prefix;
		img.uploadingImg(uImg, Img);
		Thumbnails.of(imgurlpath + Img).scale(0.5f).outputQuality(0.5).toFile(imgurlpath + newImg);
		delFile.del(imgurlpath, Img);
		baiduyun baiduyun = new baiduyun();
		Integer baiduyunAPI = baiduyun.baiduyunAPI(imgurlpath + newImg);
		if (baiduyunAPI == null) {
			delFile.del(imgurlpath, Img);
			writer.print("<script type='text/javascript'>alert('人脸头像没有检测到人脸');location.href='/web/getPageusertoapge/"
					+ cId + "';</script>");
			writer.flush();
			writer.close();
		} else {
			if (baiduyunAPI != 1) {
				delFile.del(imgurlpath, newImg);
				writer.print(
						"<script type='text/javascript'>alert('人脸头像检测到多张人脸');location.href='/web/getPageusertoapge/\"+cId+\"';</script>");
			} else {
				Fuser isnullfuser = fuserService
						.getFuserByCidAndUtel(new Fuser(null, null, null, uTel, null, null, null, cId, null, null));
				if (isnullfuser == null) {

					Fuser user = new Fuser();
					user.setcId(cId);
					user.setuIdentity(1);
					Fuser fuserBycidAnduIdentity = fuserService.getFuserBycidAnduIdentity(user);
					Fuser fuser = new Fuser(null, uName, "123456", uTel, newImg, userAdd.getuIdentity(), 1, cId,
							fuserBycidAnduIdentity.getuId(), eId);
					int isfuseradd = fuserService.fuserAdd(fuser);
					if (isfuseradd > 0) {
						Fuser fuserByCidAndUtel = fuserService.getFuserByCidAndUtel(
								new Fuser(null, null, null, uTel, null, null, null, cId, null, null));

						Integer getuId = fuserByCidAndUtel.getuId();
						String geteSn = fuser.geteSn();
						String getuName = fuser.getuName();
						String getuImg = fuser.getuImg();
						if (geteSn != null || geteSn != "") {
							if (geteSn.indexOf("-") != -1) {
								String[] sts = geteSn.split("-");
								for (int i = 0; i < sts.length; i++) {
									String str = "{typr:'adduser','uId':" + getuId + ",'uName':" + getuName + ",'uImg:'"
											+ getuImg + "}";
									WebSocketServer.sendInfo(str, sts[i]);
								}
							} else {
								String str = "{typr:'adduser','uId':" + getuId + ",'uName':" + getuName + ",'uImg:'"
										+ getuImg + "}";
								WebSocketServer.sendInfo(str, str);
							}
						}

						writer.print(
								"<script type='text/javascript'>alert('添加成功，员工登录密码为：123456');location.href='/web/getPageusertoapge/"
										+ cId + "';</script>");
						writer.flush();
						writer.close();
					} else {
						writer.print(
								"<script type='text/javascript'>alert('该员工已被注册');location.href='/web/getPageusertoapge/"
										+ cId + "';</script>");
						writer.flush();
						writer.close();
					}
				} else {
					writer.print("<script type='text/javascript'>alert('注册失败');location.href='/web/getPageusertoapge/"
							+ cId + "';</script>");
					writer.flush();
					writer.close();
				}
			}
		}
	}

	/**
	 * 查询单个员工
	 * 
	 * @param uId
	 * @param model
	 * @return
	 */
	@RequestMapping("/usertoupd/{uId}")
	public @ResponseBody SimpleResult usertoupd(@PathVariable("uId") int uId, Model model) {
		return new SimpleResult(fuserService.getFuserByuId(uId));
	}

	/**
	 * 修改员工信息
	 * 
	 * @param userAdd
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws EncodeException
	 */
	@RequestMapping("/userdoupd")
	public String userdoupd(userAdd userAdd, HttpServletResponse response) throws IOException, EncodeException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		MultipartFile uImg = null;
		if (!userAdd.getuImg().isEmpty()) {
			uImg = userAdd.getuImg();
		}
		String uName = null;
		if (userAdd.getuName() != null) {
			uName = userAdd.getuName();
		}
		String uTel = null;
		if (userAdd.getuTel() != null) {
			uTel = userAdd.getuTel();
		}
		String[] geteId = null;
		if (userAdd.geteSn() != null) {
			geteId = userAdd.geteSn();
		}
		int uIdentity = 0;
		if (userAdd.getuIdentity() != null) {
			uIdentity = userAdd.getuIdentity();
		}
		String eId = "";
		int uId = userAdd.getuId();
		Fuser olduser = fuserService.getFuserByuId(uId);
		if (geteId != null) {
			for (int i = 0; i < geteId.length; i++) {
				if (i == geteId.length - 1) {
					eId += geteId[i];
				} else {
					eId = eId + geteId[i] + "-";
				}
			}
		}
		img img = new img();
		String newImg;
		delFile delFile = new delFile();
		String timeString = System.currentTimeMillis() + "";
		if (uImg != null && !uImg.isEmpty()) {
			String originalFilename = uImg.getOriginalFilename();
			String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
			String Img = timeString + prefix;
			newImg = timeString + "-thumbnail" + prefix;
			img.uploadingImg(uImg, Img);
			Thumbnails.of(imgurlpath + Img).scale(0.5f).outputQuality(0.5f).toFile(imgurlpath + newImg);
			delFile.del(imgurlpath, Img);
			String getcImg = olduser.getuImg();
			delFile.del(imgurlpath, getcImg);
		} else {
			newImg = null;
		}
		int is = fuserService.updateFuser(new Fuser(uId, uName, null, uTel, newImg, uIdentity, 1, null, null, eId));
		if (is > 0) {
			Fuser fuser = fuserService.getFuserByuId(uId);
			Integer getuId = fuser.getuId();
			String getuName = fuser.getuName();
			String getuImg = fuser.getuImg();
			if (olduser.geteSn() != null || olduser.geteSn() != "") {
				if (olduser.geteSn().indexOf("-") != -1) {
					String[] sts = olduser.geteSn().split("-");
					for (int i = 0; i < sts.length; i++) {
						String str = "{typr:'deluser','uId':" + getuId 
								+ "}";
						WebSocketServer.sendInfo(str, sts[i]);
					}
				} else {
					String str = "{typr:'deluser','uId':" + getuId 
							+ "}";
					WebSocketServer.sendInfo(str, olduser.geteSn());
				}
			}
			if (geteId != null) {
				for (int i = 0; i < geteId.length; i++) {
					String str = "{typr:'adduser','uId':" + getuId + ",'uName':" + getuName + ",'uImg:'" + getuImg
							+ "}";
					WebSocketServer.sendInfo(str, geteId[i]);
				}
			}
			return "page/staffManagement/user_list";
		} else {
			delFile.del(imgurlpath, newImg);
			writer.print(
					"<script type='text/javascript'>alert(修改失败!');location.href='/page/staffManagement/user_list';</script>");
			writer.flush();
			writer.close();
			return null;
		}
	}

	@Resource
	private AttendanceConfigService AttendanceConfigService;

	/**
	 * 获取打卡设置
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/getAttendanceSetting")
	public @ResponseBody SimpleResult getAttendanceSetting(HttpSession session) {
		Fuser att = (Fuser) session.getAttribute("user");
		AttendanceConfig attendanceConfigByCid = AttendanceConfigService.getAttendanceConfigByCid(att.getcId());
		return new SimpleResult(attendanceConfigByCid);

	}

	/**
	 * 设置打卡
	 * 
	 * @param config
	 * @param session
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws EncodeException
	 */
	@RequestMapping("/attendanceSetting")
	public String attendanceSetting(AttendanceConfigAdd config, HttpSession session, HttpServletResponse response)
			throws IOException, EncodeException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		Fuser user = (Fuser) session.getAttribute("user");
		AttendanceConfig oldattendanceConfig = AttendanceConfigService.getAttendanceConfigByCid(user.getcId());
		String[] workdayarr = config.getWorkday();
		String workday = "";

		for (int i = 0; i < workdayarr.length; i++) {
			if (i == workdayarr.length - 1) {
				workday += workdayarr[i];
			} else {
				workday = workday + workdayarr[i] + "-";
			}
		}
		AttendanceConfig attendanceConfig = new AttendanceConfig(null, config.getAttendanceTime(),
				config.getClosingTime(), workday, user.getcId());
		if (oldattendanceConfig == null) {
			int addAttendanceConfig = AttendanceConfigService.addAttendanceConfig(attendanceConfig);
			if (addAttendanceConfig > 0) {
				return "page/attendanceManagement/getAttendanceRecord";
			} else {
				writer.print(
						"<script type='text/javascript'>alert(修改失败!');location.href='/page/staffManagement/user_list';</script>");
				writer.flush();
				writer.close();
				return null;
			}
		} else {
			attendanceConfig.setAcId(oldattendanceConfig.getAcId());
			int is = AttendanceConfigService.updAttendanceConfig(attendanceConfig);
			if (is > 0) {
				return "page/attendanceManagement/getAttendanceRecord";
			} else {
				writer.print(
						"<script type='text/javascript'>alert(修改失败!');location.href='/page/staffManagement/user_list';</script>");
				writer.flush();
				writer.close();
				return null;
			}

		}

	}

	/**
	 * 获取个人信息
	 * 
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping("/getpersonalDetails")
	public String personalDetails(HttpSession session, Model model) {
		Fuser user = (Fuser) session.getAttribute("user");
		Fuser fuser = fuserService.getFuserByuId(user.getuId());
		model.addAttribute("user", fuser);
		return "page/personalDetails/user_upd";
	}

	/**
	 * 修改个人信息
	 * 
	 * @param userAdd
	 * @param response
	 * @return
	 * @throws IOException
	 * @throws EncodeException
	 */
	@RequestMapping("/setpersonalDetails")
	public String setpersonalDetails(userAdd userAdd, HttpServletResponse response)
			throws IOException, EncodeException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();
		MultipartFile uImg = userAdd.getuImg();
		String uName = userAdd.getuName();
		String uTel = userAdd.getuTel();
		int uId = userAdd.getuId();
		Fuser olduser = fuserService.getFuserByuId(uId);
		img img = new img();
		String newImg;
		delFile delFile = new delFile();
		String timeString = System.currentTimeMillis() + "";
		if (!uImg.isEmpty()) {
			String originalFilename = uImg.getOriginalFilename();
			String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
			String Img = timeString + prefix;
			newImg = timeString + "-thumbnail" + prefix;
			img.uploadingImg(uImg, Img);
			Thumbnails.of(imgurlpath + Img).scale(0.5f).outputQuality(0.5f).toFile(imgurlpath + newImg);
			delFile.del(imgurlpath, Img);

		} else {
			newImg = null;
		}
		baiduyun baiduyun = new baiduyun();
		Integer baiduyunAPI = baiduyun.baiduyunAPI(imgurlpath + newImg);
		if (baiduyunAPI == null) {
			delFile.del(imgurlpath, newImg);
			writer.print(
					"<script type='text/javascript'>alert('人脸头像没有检测到人脸');location.href='/web/getpersonalDetails';</script>");
			writer.flush();
			writer.close();
		} else {
			if (baiduyunAPI != 1) {
				delFile.del(imgurlpath, newImg);
				writer.print(
						"<script type='text/javascript'>alert('人脸头像检测到多张人脸');location.href='/web/getpersonalDetails';</script>");
			} else {

				int is = fuserService.updateFuser(new Fuser(uId, uName, null, uTel, newImg, null, 1, null, null, null));
				if (is > 0) {
					String getcImg = olduser.getuImg();
					delFile.del(imgurlpath, getcImg);
					Fuser fuser = fuserService.getFuserByuId(uId);
					Integer getuId = fuser.getuId();
					String geteSn = fuser.geteSn();
					String getuName = fuser.getuName();
					String getuImg = fuser.getuImg();
					if (geteSn != null && !geteSn.equals("")) {
						if (geteSn.indexOf("-") != -1) {
							String[] st = geteSn.split("-");
							for (int i = 0; i < st.length; i++) {
								String str = "{typr:'upduser',uId:" + getuId + ",'uName':" + getuName + ",'uImg:'"
										+ getuImg + "}";
								boolean sendInfo = WebSocketServer.sendInfo(str, st[i]);
							}
						} else {
							String str = "{typr:'upduser',uId:" + getuId + ",'uName':" + getuName + ",'uImg:'" + getuImg
									+ "}";
							boolean sendInfo = WebSocketServer.sendInfo(str, str);
						}

					}

					return "redirect:/web/getpersonalDetails";
				} else {
					delFile.del(imgurlpath, newImg);
					writer.print(
							"<script type='text/javascript'>alert(修改失败!');location.href='/web/getpersonalDetails';</script>");
					writer.flush();
					writer.close();
					return null;
				}
			}

		}
		return null;
	}

	/**
	 * 退出登录
	 * 
	 * @param session
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		if (session != null) {
			session.invalidate();// 关闭session
		}
		return "redirect:/redirect/tologin";
	}

	@Resource
	private TravelRecordsService TravelRecordsService;

	/**
	 * 出入历史查询
	 */
	@RequestMapping("/getAlltravelRecords/{page}")
	public @ResponseBody SimpleResult getAlltravelRecords(@PathVariable("page") int page, HttpSession session) {
		Fuser user = (Fuser) session.getAttribute("user");
		List<TravelRecords> arr = TravelRecordsService.getAlltravelRecords(user.getcId());
		int size = arr.size();
		int pageindex = 0;
		int pagemax;
		if (size % 30 == 0) {
			pagemax = size / 30;
		} else {
			pagemax = size / 30 + 1;
		}
		if (page > 1)
			pageindex = (page - 1) * 30;
		pageselect pageselect = new pageselect(pageindex, 30, null, user.getcId());
		List<TravelRecords> getAlltravelRecordsPage = TravelRecordsService.getAlltravelRecordsPage(pageselect);
		List<travelRecordsBean> beans = new ArrayList<travelRecordsBean>();
		for (TravelRecords t : getAlltravelRecordsPage) {
			Integer getuId = t.getuId();
			Integer getcId = t.getcId();
			String strangerImg = t.getStrangerImg();
			Integer gettId = t.gettId();
			String gettTime = t.gettTime();
			Fuser fuserByuId = fuserService.getFuserByuId(getuId);
			String getuImg = fuserByuId.getuImg();
			Equipment equipmentBySn = equipmentService.getEquipmentBySn(t.geteSn());
			if (equipmentBySn == null || equipmentBySn.equals("")) {
				beans.add(new travelRecordsBean(gettId, gettTime, fuserByuId.getuName(), getcId, strangerImg, getuImg,
						"该设备已删除"));
			} else {
				beans.add(new travelRecordsBean(gettId, gettTime, fuserByuId.getuName(), getcId, strangerImg, getuImg,
						equipmentBySn.geteName()));
			}

		}

		return new SimpleResult(beans, pagemax);

	}

	/**
	 * 分页查询陌生人抓拍记录
	 * 
	 * @param page
	 * @param session
	 * @return
	 */
	@RequestMapping("/getAllstrangerRecordsPage/{page}")
	public @ResponseBody SimpleResult getAllstrangerRecordsPage(@PathVariable("page") int page, HttpSession session) {
		Fuser user = (Fuser) session.getAttribute("user");
		Company companyByCid = companyService.getCompanyByCid(user.getcId());
		List<TravelRecords> allstrangerRecords = new ArrayList<TravelRecords>();
		String geteSn = companyByCid.geteSn();
		int pagemax = 0;
		if (geteSn != null && !geteSn.equals("")) {
			if (geteSn.indexOf("-") != -1) {
				String[] st = geteSn.split("-");
				List<String> strarr = new ArrayList<String>();
				for (String s : st) {
					strarr.add(s);
				}

				List<TravelRecords> arr = TravelRecordsService.getAllstrangerRecords(strarr);
				int size = arr.size();

				int pageindex = 0;
				if (size % 30 == 0) {
					pagemax = size / 30;
				} else {
					pagemax = size / 30 + 1;
				}
				if (page > 1)
					pageindex = (page - 1) * 30;
				int count = 0;
				for (int i = 0; i < arr.size(); i++) {
					if (i == pageindex || i > pageindex) {
						if (count < 30) {
							allstrangerRecords.add(arr.get(i));
							count++;
						}
					}
				}
			} else {
				List<String> strarr = new ArrayList<String>();
				strarr.add(geteSn);
				List<TravelRecords> arr = TravelRecordsService.getAllstrangerRecords(strarr);
				int size = arr.size();

				int pageindex = 0;
				if (size % 30 == 0) {
					pagemax = size / 30;
				} else {
					pagemax = size / 30 + 1;
				}
				if (page > 1)
					pageindex = (page - 1) * 30;
				int count = 0;
				for (int i = 0; i < arr.size(); i++) {
					if (i == pageindex || i > pageindex) {
						if (count < 20) {
							allstrangerRecords.add(arr.get(i));
							count++;
						}
					}
				}
			}
		}
		List<travelRecordsBean> recordsBeans = new ArrayList<travelRecordsBean>();
		for (TravelRecords travelRecords : allstrangerRecords) {
			String strangerImg = travelRecords.getStrangerImg();
			String eSn = travelRecords.geteSn();
			Integer tId = travelRecords.gettId();
			Equipment equipmentBySn = equipmentService.getEquipmentBySn(eSn);
			String tTime = travelRecords.gettTime();
			recordsBeans
					.add(new travelRecordsBean(tId, tTime, null, null, strangerImg, null, equipmentBySn.geteName()));
		}

		return new SimpleResult(recordsBeans, pagemax);

	}

	@Resource
	private AttendanceRecordService AttendanceRecordService;

	/**
	 * 获取公司所有员工的考勤记录
	 * 
	 * @param y
	 * @param m
	 * @param session
	 * @return
	 */
	@RequestMapping("/getAttendanceRecord/{y}/{m}")
	public @ResponseBody SimpleResult getAttendanceRecord(@PathVariable("y") int y, @PathVariable("m") int m,
			HttpSession session) {
		Fuser user = (Fuser) session.getAttribute("user");
		List<getAttendanceRecord> record = new ArrayList<getAttendanceRecord>();
		if (user.getuIdentity() != 3) {
			List<Fuser> fusersAllByCid = fuserService.getFusersAllByCid(user.getcId());
			for (Fuser fuser : fusersAllByCid) {
				Integer cId = user.getcId();
				String uName = fuser.getuName();
				int beLateNum = 0;
				int leaveEarlyNum = 0;
				int oughtToWorkDay = 0;
				int oughtToAttendanceNum = 0;
				AttendanceConfig attendanceConfigByCid = AttendanceConfigService.getAttendanceConfigByCid(cId);
				if (attendanceConfigByCid != null) {

					String[] st = attendanceConfigByCid.getWorkday().split("-");
					List<Integer> workday = new ArrayList<Integer>();

					for (int i = 0; i < st.length; i++) {
						workday.add(Integer.valueOf(st[i]));
					}

					String mt = "";
					if (m < 10) {
						mt = "0" + m;
					} else {
						mt = m + "";
					}

					List<AttendanceRecord> allAttendanceRecordByUid = AttendanceRecordService
							.getAllAttendanceRecordByUidandday(new selAttendanceRecord(fuser.getuId(), y + "-" + mt));
					if (allAttendanceRecordByUid.size() != 0) {

						int sumday = WanNianLi.formatCalendarOutput(y, m);
						for (int i = 1; i <= sumday; i++) {
							int getweekDay = WanNianLi.getweekDay(y, m, i);
							for (int j = 0; j < workday.size(); j++) {
								Integer integer = workday.get(j);
								if (integer == getweekDay) {
									oughtToWorkDay++;
								}
							}

							for (AttendanceRecord a : allAttendanceRecordByUid) {
								String arTime = a.getArTime();
								String[] date = arTime.split("\\s+");
								String nowdate = y + "-" + mt + "-" + i;
								List<AttendanceRecord> dAttendanceRecords = new ArrayList<AttendanceRecord>();
								if (date[0].equals(nowdate)) {
									dAttendanceRecords.add(a);
								}
								if (dAttendanceRecords.size() != 2) {
									for (AttendanceRecord d : dAttendanceRecords) {
										Integer status = d.getStatus();
										if (status == 3) {
											beLateNum++;
										} else if (status == 4) {
											leaveEarlyNum++;
										}
									}
								}
							}
						}
						oughtToAttendanceNum = oughtToWorkDay * 2;
						String dString = y + "-" + m;
						getAttendanceRecord r = new getAttendanceRecord(fuser.getuId(), uName, oughtToAttendanceNum,
								allAttendanceRecordByUid.size(), beLateNum, leaveEarlyNum,
								oughtToAttendanceNum - allAttendanceRecordByUid.size(), oughtToWorkDay, dString);
						record.add(r);
					} else {

						int sumday = WanNianLi.formatCalendarOutput(y, m);
						for (int i = 1; i <= sumday; i++) {
							int getweekDay = WanNianLi.getweekDay(y, m, i);
							for (int j = 0; j < workday.size(); j++) {
								Integer integer = workday.get(j);
								if (integer == getweekDay) {
									oughtToWorkDay++;
								}
							}
							oughtToAttendanceNum = oughtToWorkDay * 2;

						}
						String dString = y + "-" + m;
						getAttendanceRecord r = new getAttendanceRecord(fuser.getuId(), uName, oughtToAttendanceNum,
								allAttendanceRecordByUid.size(), beLateNum, leaveEarlyNum,
								oughtToAttendanceNum - allAttendanceRecordByUid.size(), oughtToWorkDay, dString);
						record.add(r);
					}

				}
			}
			return new SimpleResult(record);
		} else {
			Integer cId = user.getcId();
			String uName = user.getuName();

			AttendanceConfig attendanceConfigByCid = AttendanceConfigService.getAttendanceConfigByCid(cId);
			if (attendanceConfigByCid != null) {

				String[] st = attendanceConfigByCid.getWorkday().split("-");
				List<Integer> workday = new ArrayList<Integer>();

				for (int i = 0; i < st.length; i++) {
					workday.add(Integer.valueOf(st[i]));
				}

				String mt = "";
				if (m < 10) {
					mt = "0" + m;
				} else {
					mt = m + "";
				}

				for (int z = 1; z <= 12; z++) {
					int beLateNum = 0;
					int leaveEarlyNum = 0;
					int oughtToWorkDay = 0;
					int oughtToAttendanceNum = 0;
					List<AttendanceRecord> allAttendanceRecordByUid = AttendanceRecordService
							.getAllAttendanceRecordByUidandday(new selAttendanceRecord(user.getuId(), y + "-" + z));
					if (allAttendanceRecordByUid.size() != 0) {

						int sumday = WanNianLi.formatCalendarOutput(y, z);
						for (int i = 1; i <= sumday; i++) {
							int getweekDay = WanNianLi.getweekDay(y, z, i);
							for (int j = 0; j < workday.size(); j++) {
								Integer integer = workday.get(j);
								if (integer == getweekDay) {
									oughtToWorkDay++;
								}
							}

							for (AttendanceRecord a : allAttendanceRecordByUid) {
								String arTime = a.getArTime();
								String[] date = arTime.split("\\s+");
								String nowdate = y + "-" + z + "-" + i;
								List<AttendanceRecord> dAttendanceRecords = new ArrayList<AttendanceRecord>();
								if (date[0].equals(nowdate)) {
									dAttendanceRecords.add(a);
								}
								if (dAttendanceRecords.size() != 2) {
									for (AttendanceRecord d : dAttendanceRecords) {
										Integer status = d.getStatus();
										if (status == 3) {
											beLateNum++;
										} else if (status == 4) {
											leaveEarlyNum++;
										}
									}
								}
							}
						}
						oughtToAttendanceNum = oughtToWorkDay * 2;
						String dString = y + "-" + z;
						getAttendanceRecord r = new getAttendanceRecord(user.getuId(), uName, oughtToAttendanceNum,
								allAttendanceRecordByUid.size(), beLateNum, leaveEarlyNum,
								oughtToAttendanceNum - allAttendanceRecordByUid.size(), oughtToWorkDay, dString);
						record.add(r);
					} else {

						int sumday = WanNianLi.formatCalendarOutput(y, z);
						for (int i = 1; i <= sumday; i++) {
							int getweekDay = WanNianLi.getweekDay(y, z, i);
							for (int j = 0; j < workday.size(); j++) {
								Integer integer = workday.get(j);
								if (integer == getweekDay) {
									oughtToWorkDay++;
								}
							}
							oughtToAttendanceNum = oughtToWorkDay * 2;

						}
						String dString = y + "-" + z;
						getAttendanceRecord r = new getAttendanceRecord(user.getuId(), uName, oughtToAttendanceNum,
								allAttendanceRecordByUid.size(), beLateNum, leaveEarlyNum,
								oughtToAttendanceNum - allAttendanceRecordByUid.size(), oughtToWorkDay, dString);
						record.add(r);
					}

				}
			}
			return new SimpleResult(record);
		}
	}

	/**
	 * 获取员工考勤记录
	 * 
	 * @param uid
	 * @param y
	 * @param m
	 * @param model
	 * @return
	 */
	@RequestMapping("/getAttendanceRecordByUid/{uid}/{y}/{m}")
	public String getAttendanceRecordByUid(@PathVariable("uid") int uid, @PathVariable("y") int y,
			@PathVariable("m") int m, Model model) {
		Fuser user = fuserService.getFuserByuId(uid);
		Integer cId = user.getcId();
		AttendanceConfig attendanceConfigByCid = AttendanceConfigService.getAttendanceConfigByCid(cId);
		List<ClockInForDetails> arr = new ArrayList<ClockInForDetails>();
		if (attendanceConfigByCid != null) {

			String[] st = {};
			if (attendanceConfigByCid.getWorkday() != null && !attendanceConfigByCid.getWorkday().equals("")
					&& attendanceConfigByCid.getWorkday().indexOf("-") != -1) {
				st = attendanceConfigByCid.getWorkday().split("-");
			} else {
				st[0] = attendanceConfigByCid.getWorkday();
			}

			String mt = "";
			if (m < 10) {
				mt = "0" + m;
			} else {
				mt = m + "";
			}

			int sumday = WanNianLi.formatCalendarOutput(y, m);

			for (int i = 1; i <= sumday; i++) {
				String nowdate = "";
				if (i < 10) {
					nowdate = y + "-" + mt + "-0" + i;
				} else {
					nowdate = y + "-" + mt + "-" + i;
				}
				List<AttendanceRecord> datadadt = AttendanceRecordService
						.getAllAttendanceRecordByUidandday(new selAttendanceRecord(uid, nowdate));
				if (datadadt.size() == 1) {
					if (datadadt.get(0).getStatus() == 1 || datadadt.get(0).getStatus() == 3) {
						String arTime = datadadt.get(0).getArTime();
						String clockInStatus = "";
						if (datadadt.get(0).getStatus() == 1) {
							clockInStatus = "正常";
						} else if (datadadt.get(0).getStatus() == 3) {
							clockInStatus = "迟到";
						}
						String timeToPunchOut = "无";
						String toPunchOutStatus = "缺勤";
						String isWorkDay = "n";
						String getweekDay = WanNianLi.getweekDay(y, m, i) + "";
						for (int j = 0; j < st.length; j++) {
							String cString = st[j];
							if (cString.equals(getweekDay)) {
								isWorkDay = "y";
							}
						}
						ClockInForDetails clockInForDetails = new ClockInForDetails(nowdate, arTime, clockInStatus,
								timeToPunchOut, toPunchOutStatus, isWorkDay, y, m, uid);
						arr.add(clockInForDetails);
					} else if (datadadt.get(0).getStatus() == 2 || datadadt.get(0).getStatus() == 4) {
						String timeToPunchOut = datadadt.get(0).getArTime();
						String toPunchOutStatus = "";
						if (datadadt.get(0).getStatus() == 2) {
							toPunchOutStatus = "正常";
						} else if (datadadt.get(0).getStatus() == 4) {
							toPunchOutStatus = "早退";
						}
						String timeToClockIn = "无";
						String clockInStatus = "缺勤";
						String isWorkDay = "n";
						String getweekDay = WanNianLi.getweekDay(y, m, i) + "";
						for (int j = 0; j < st.length; j++) {
							String cString = st[j];
							if (cString.equals(getweekDay)) {
								isWorkDay = "y";
							}
						}
						ClockInForDetails clockInForDetails = new ClockInForDetails(nowdate, timeToClockIn,
								clockInStatus, timeToPunchOut, toPunchOutStatus, isWorkDay, y, m, uid);
						arr.add(clockInForDetails);
					}
				} else if (datadadt.size() == 2) {
					String timeToClockIn = "";
					String clockInStatus = "";
					String timeToPunchOut = "";
					String toPunchOutStatus = "";
					for (AttendanceRecord att : datadadt) {
						if (att.getStatus() == 1 || att.getStatus() == 3) {
							timeToClockIn += att.getArTime();
							if (att.getStatus() == 1) {
								clockInStatus = "正常";
							} else if (att.getStatus() == 3) {
								clockInStatus = "迟到";
							}
						} else if (att.getStatus() == 2 || att.getStatus() == 4) {
							timeToPunchOut = att.getArTime();
							if (att.getStatus() == 2) {
								toPunchOutStatus = "正常";
							} else if (att.getStatus() == 4) {
								toPunchOutStatus = "早退";
							}
						}
					}
					String isWorkDay = "n";
					String getweekDay = WanNianLi.getweekDay(y, m, i) + "";
					for (int j = 0; j < st.length; j++) {
						String cString = st[j];
						if (cString.equals(getweekDay)) {
							isWorkDay = "y";
						}
					}
					ClockInForDetails clockInForDetails = new ClockInForDetails(nowdate, timeToClockIn, clockInStatus,
							timeToPunchOut, toPunchOutStatus, isWorkDay, y, m, uid);
					arr.add(clockInForDetails);
				} else if (datadadt.size() == 0) {
					String isWorkDay = "n";
					String getweekDay = WanNianLi.getweekDay(y, m, i) + "";
					for (int j = 0; j < st.length; j++) {
						String cString = st[j];
						if (cString.equals(getweekDay)) {
							isWorkDay = "y";
						}
					}
					if (isWorkDay.equals("y")) {
						ClockInForDetails clockInForDetails = new ClockInForDetails(nowdate, "无", "缺勤", "无", "缺勤",
								isWorkDay, y, m, uid);
						arr.add(clockInForDetails);
					} else {
						ClockInForDetails clockInForDetails = new ClockInForDetails(nowdate, "无", "无", "无", "无",
								isWorkDay, y, m, uid);
						arr.add(clockInForDetails);
					}
				}
			}

		}
		model.addAttribute("arr", arr);
		return "page/attendanceManagement/getAttendanceRecordByUid";
	}

	@RequestMapping("/getstrangerRecordsliketTime/{tTime}")
	public @ResponseBody SimpleResult getstrangerRecordsliketTime(@PathVariable("tTime") String tTime) {
		List<TravelRecords> getstrangerRecordsliketTime = TravelRecordsService.getstrangerRecordsliketTime(tTime);
		return new SimpleResult(getstrangerRecordsliketTime);
	}

	/**
	 * 公司所有员考勤记录导出
	 * 
	 * @param y
	 * @param m
	 * @param response
	 * @param session
	 * @throws Exception
	 */
	@RequestMapping("/getAttendanceRecordtoEecel/{y}/{m}")
	public void getAttendanceRecordtoEecel(@PathVariable("y") int y, @PathVariable("m") int m,
			HttpServletResponse response, HttpSession session) throws Exception {
		Fuser user = (Fuser) session.getAttribute("user");
		List<getAttendanceRecord> record = new ArrayList<getAttendanceRecord>();
		if (user.getuIdentity() != 3) {
			List<Fuser> fusersAllByCid = fuserService.getFusersAllByCid(user.getcId());
			for (Fuser fuser : fusersAllByCid) {
				Integer cId = user.getcId();
				String uName = fuser.getuName();
				int beLateNum = 0;
				int leaveEarlyNum = 0;
				int oughtToWorkDay = 0;
				int oughtToAttendanceNum = 0;
				AttendanceConfig attendanceConfigByCid = AttendanceConfigService.getAttendanceConfigByCid(cId);
				if (attendanceConfigByCid != null) {
					String[] st = attendanceConfigByCid.getWorkday().split("-");
					List<Integer> workday = new ArrayList<Integer>();

					for (int i = 0; i < st.length; i++) {
						workday.add(Integer.valueOf(st[i]));
					}

					String mt = "";
					if (m < 10) {
						mt = "0" + m;
					} else {
						mt = m + "";
					}

					List<AttendanceRecord> allAttendanceRecordByUid = AttendanceRecordService
							.getAllAttendanceRecordByUidandday(new selAttendanceRecord(fuser.getuId(), y + "-" + mt));
					if (allAttendanceRecordByUid.size() != 0) {

						int sumday = WanNianLi.formatCalendarOutput(y, m);
						for (int i = 1; i <= sumday; i++) {
							int getweekDay = WanNianLi.getweekDay(y, m, i);
							for (int j = 0; j < workday.size(); j++) {
								Integer integer = workday.get(j);
								if (integer == getweekDay) {
									oughtToWorkDay++;
								}
							}

							for (AttendanceRecord a : allAttendanceRecordByUid) {
								String arTime = a.getArTime();
								String[] date = arTime.split("\\s+");
								String nowdate = y + "-" + mt + "-" + i;
								List<AttendanceRecord> dAttendanceRecords = new ArrayList<AttendanceRecord>();
								if (date[0].equals(nowdate)) {
									dAttendanceRecords.add(a);
								}
								if (dAttendanceRecords.size() != 2) {
									for (AttendanceRecord d : dAttendanceRecords) {
										Integer status = d.getStatus();
										if (status == 3) {
											beLateNum++;
										} else if (status == 4) {
											leaveEarlyNum++;
										}
									}
								}
							}
						}
						String dString = y + "-" + m;
						oughtToAttendanceNum = oughtToWorkDay * 2;
						getAttendanceRecord r = new getAttendanceRecord(fuser.getuId(), uName, oughtToAttendanceNum,
								allAttendanceRecordByUid.size(), beLateNum, leaveEarlyNum,
								oughtToAttendanceNum - allAttendanceRecordByUid.size(), oughtToWorkDay, dString);
						record.add(r);
					} else {

						int sumday = WanNianLi.formatCalendarOutput(y, m);
						for (int i = 1; i <= sumday; i++) {
							int getweekDay = WanNianLi.getweekDay(y, m, i);
							for (int j = 0; j < workday.size(); j++) {
								Integer integer = workday.get(j);
								if (integer == getweekDay) {
									oughtToWorkDay++;
								}
							}
							oughtToAttendanceNum = oughtToWorkDay * 2;

						}
						String dString = y + "-" + m;
						getAttendanceRecord r = new getAttendanceRecord(fuser.getuId(), uName, oughtToAttendanceNum,
								allAttendanceRecordByUid.size(), beLateNum, leaveEarlyNum,
								oughtToAttendanceNum - allAttendanceRecordByUid.size(), oughtToWorkDay, dString);
						record.add(r);
					}
				}
			}
			ExcelData data = new ExcelData();
			Company companyByCid = companyService.getCompanyByCid(user.getcId());
			String dataName = y + "-" + m + companyByCid.getcName() + "员工考勤统计";
			data.setName(dataName);
			List<String> titles = new ArrayList();
			titles.add("姓名");
			titles.add("本月工作日天数");
			titles.add("应打卡次数");
			titles.add("实际打卡次数");
			titles.add("迟到次数");
			titles.add("早退次数");
			titles.add("缺勤次数");
			data.setTitles(titles);
			List<List<Object>> rows = new ArrayList();
			List<Object> row = null;
			for (getAttendanceRecord re : record) {
				row = new ArrayList();
				row.add(re.getuName());
				row.add(re.getWorkDayNum());
				row.add(re.getOughtToAttendanceNum());
				row.add(re.getVirtualAttendanceNum());
				row.add(re.getBeLateNum());
				row.add(re.getLeaveEarlyNum());
				row.add(re.getAbsenceFromDutyNum());
				rows.add(row);
			}

			data.setRows(rows);
			String fileName = dataName + ".xls";
			ExcelUtils.exportExcel(response, fileName, data);
		} else {
			Integer cId = user.getcId();
			String uName = user.getuName();
			int beLateNum = 0;
			int leaveEarlyNum = 0;
			int oughtToWorkDay = 0;
			int oughtToAttendanceNum = 0;
			AttendanceConfig attendanceConfigByCid = AttendanceConfigService.getAttendanceConfigByCid(cId);
			if (attendanceConfigByCid != null) {

				String[] st = attendanceConfigByCid.getWorkday().split("-");
				List<Integer> workday = new ArrayList<Integer>();

				for (int i = 0; i < st.length; i++) {
					workday.add(Integer.valueOf(st[i]));
				}

				String mt = "";
				if (m < 10) {
					mt = "0" + m;
				} else {
					mt = m + "";
				}

				List<AttendanceRecord> allAttendanceRecordByUid = AttendanceRecordService
						.getAllAttendanceRecordByUidandday(new selAttendanceRecord(user.getuId(), y + "-" + mt));
				if (allAttendanceRecordByUid.size() != 0) {

					int sumday = WanNianLi.formatCalendarOutput(y, m);
					for (int i = 1; i <= sumday; i++) {
						int getweekDay = WanNianLi.getweekDay(y, m, i);
						for (int j = 0; j < workday.size(); j++) {
							Integer integer = workday.get(j);
							if (integer == getweekDay) {
								oughtToWorkDay++;
							}
						}

						for (AttendanceRecord a : allAttendanceRecordByUid) {
							String arTime = a.getArTime();
							String[] date = arTime.split("\\s+");
							String nowdate = y + "-" + mt + "-" + i;
							List<AttendanceRecord> dAttendanceRecords = new ArrayList<AttendanceRecord>();
							if (date[0].equals(nowdate)) {
								dAttendanceRecords.add(a);
							}
							if (dAttendanceRecords.size() != 2) {
								for (AttendanceRecord d : dAttendanceRecords) {
									Integer status = d.getStatus();
									if (status == 3) {
										beLateNum++;
									} else if (status == 4) {
										leaveEarlyNum++;
									}
								}
							}
						}
					}
					String dString = y + "-" + m;
					oughtToAttendanceNum = oughtToWorkDay * 2;
					getAttendanceRecord r = new getAttendanceRecord(user.getuId(), uName, oughtToAttendanceNum,
							allAttendanceRecordByUid.size(), beLateNum, leaveEarlyNum,
							oughtToAttendanceNum - allAttendanceRecordByUid.size(), oughtToWorkDay, dString);
					record.add(r);
				} else {
					int sumday = WanNianLi.formatCalendarOutput(y, m);
					for (int i = 1; i <= sumday; i++) {
						int getweekDay = WanNianLi.getweekDay(y, m, i);
						for (int j = 0; j < workday.size(); j++) {
							Integer integer = workday.get(j);
							if (integer == getweekDay) {
								oughtToWorkDay++;
							}
						}
						oughtToAttendanceNum = oughtToWorkDay * 2;

					}
					String dString = y + "-" + m;
					getAttendanceRecord r = new getAttendanceRecord(user.getuId(), uName, oughtToAttendanceNum,
							allAttendanceRecordByUid.size(), beLateNum, leaveEarlyNum,
							oughtToAttendanceNum - allAttendanceRecordByUid.size(), oughtToWorkDay, dString);
					record.add(r);
				}
			}
			ExcelData data = new ExcelData();
			Company companyByCid = companyService.getCompanyByCid(user.getcId());
			String dataName = y + "-" + m + companyByCid.getcName() + "员工考勤统计";
			data.setName(dataName);
			List<String> titles = new ArrayList();
			titles.add("姓名");
			titles.add("本月工作日天数");
			titles.add("应打卡次数");
			titles.add("实际打卡次数");
			titles.add("迟到次数");
			titles.add("早退次数");
			titles.add("缺勤次数");
			data.setTitles(titles);
			List<List<Object>> rows = new ArrayList();
			List<Object> row = null;
			for (getAttendanceRecord re : record) {
				row = new ArrayList();
				row.add(re.getuName());
				row.add(re.getWorkDayNum());
				row.add(re.getOughtToAttendanceNum());
				row.add(re.getVirtualAttendanceNum());
				row.add(re.getBeLateNum());
				row.add(re.getLeaveEarlyNum());
				row.add(re.getAbsenceFromDutyNum());
				rows.add(row);
			}

			data.setRows(rows);
			String fileName = dataName + ".xls";
			ExcelUtils.exportExcel(response, fileName, data);
		}

	}

	/**
	 * 员工考勤记录详情导出
	 * 
	 * @param uid
	 * @param y
	 * @param m
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/getAttendanceRecordByUidToExcel/{uid}/{y}/{m}")
	public void getAttendanceRecordByUidToExcel(@PathVariable("uid") int uid, @PathVariable("y") int y,
			@PathVariable("m") int m, HttpServletResponse response) throws Exception {
		Fuser user = fuserService.getFuserByuId(uid);
		Integer cId = user.getcId();
		AttendanceConfig attendanceConfigByCid = AttendanceConfigService.getAttendanceConfigByCid(cId);
		if (attendanceConfigByCid != null) {
			String[] st = {};
			if (attendanceConfigByCid.getWorkday() != null && !attendanceConfigByCid.getWorkday().equals("")
					&& attendanceConfigByCid.getWorkday().indexOf("-") != -1) {
				st = attendanceConfigByCid.getWorkday().split("-");
			} else {
				st[0] = attendanceConfigByCid.getWorkday();
			}

			String mt = "";
			if (m < 10) {
				mt = "0" + m;
			} else {
				mt = m + "";
			}

			int sumday = WanNianLi.formatCalendarOutput(y, m);
			List<ClockInForDetails> arr = new ArrayList<ClockInForDetails>();
			for (int i = 1; i <= sumday; i++) {
				String nowdate = "";
				if (i < 10) {
					nowdate = y + "-" + mt + "-0" + i;
				} else {
					nowdate = y + "-" + mt + "-" + i;
				}
				List<AttendanceRecord> datadadt = AttendanceRecordService
						.getAllAttendanceRecordByUidandday(new selAttendanceRecord(uid, nowdate));
				if (datadadt.size() == 1) {
					if (datadadt.get(0).getStatus() == 1 || datadadt.get(0).getStatus() == 3) {
						String arTime = datadadt.get(0).getArTime();
						String clockInStatus = "";
						if (datadadt.get(0).getStatus() == 1) {
							clockInStatus = "正常";
						} else if (datadadt.get(0).getStatus() == 3) {
							clockInStatus = "迟到";
						}
						String timeToPunchOut = "无";
						String toPunchOutStatus = "缺勤";
						String isWorkDay = "n";
						String getweekDay = WanNianLi.getweekDay(y, m, i) + "";
						for (int j = 0; j < st.length; j++) {
							String cString = st[j];
							if (cString.equals(getweekDay)) {
								isWorkDay = "y";
							}
						}
						ClockInForDetails clockInForDetails = new ClockInForDetails(nowdate, arTime, clockInStatus,
								timeToPunchOut, toPunchOutStatus, isWorkDay, y, m, uid);
						arr.add(clockInForDetails);
					} else if (datadadt.get(0).getStatus() == 2 || datadadt.get(0).getStatus() == 4) {
						String timeToPunchOut = datadadt.get(0).getArTime();
						String toPunchOutStatus = "";
						if (datadadt.get(0).getStatus() == 2) {
							toPunchOutStatus = "正常";
						} else if (datadadt.get(0).getStatus() == 4) {
							toPunchOutStatus = "早退";
						}
						String timeToClockIn = "无";
						String clockInStatus = "缺勤";
						String isWorkDay = "n";
						String getweekDay = WanNianLi.getweekDay(y, m, i) + "";
						for (int j = 0; j < st.length; j++) {
							String cString = st[j];
							if (cString.equals(getweekDay)) {
								isWorkDay = "y";
							}
						}
						ClockInForDetails clockInForDetails = new ClockInForDetails(nowdate, timeToClockIn,
								clockInStatus, timeToPunchOut, toPunchOutStatus, isWorkDay, y, m, uid);
						arr.add(clockInForDetails);
					}
				} else if (datadadt.size() == 2) {
					String timeToClockIn = "";
					String clockInStatus = "";
					String timeToPunchOut = "";
					String toPunchOutStatus = "";
					for (AttendanceRecord att : datadadt) {
						if (att.getStatus() == 1 || att.getStatus() == 3) {
							timeToClockIn += att.getArTime();
							if (att.getStatus() == 1) {
								clockInStatus = "正常";
							} else if (att.getStatus() == 3) {
								clockInStatus = "迟到";
							}
						} else if (att.getStatus() == 2 || att.getStatus() == 4) {
							timeToPunchOut = att.getArTime();
							if (att.getStatus() == 2) {
								toPunchOutStatus = "正常";
							} else if (att.getStatus() == 4) {
								toPunchOutStatus = "早退";
							}
						}
					}
					String isWorkDay = "n";
					String getweekDay = WanNianLi.getweekDay(y, m, i) + "";
					for (int j = 0; j < st.length; j++) {
						String cString = st[j];
						if (cString.equals(getweekDay)) {
							isWorkDay = "y";
						}
					}
					ClockInForDetails clockInForDetails = new ClockInForDetails(nowdate, timeToClockIn, clockInStatus,
							timeToPunchOut, toPunchOutStatus, isWorkDay, y, m, uid);
					arr.add(clockInForDetails);
				} else if (datadadt.size() == 0) {
					String isWorkDay = "n";
					String getweekDay = WanNianLi.getweekDay(y, m, i) + "";
					for (int j = 0; j < st.length; j++) {
						String cString = st[j];
						if (cString.equals(getweekDay)) {
							isWorkDay = "y";
						}
					}
					if (isWorkDay.equals("y")) {
						ClockInForDetails clockInForDetails = new ClockInForDetails(nowdate, "无", "缺勤", "无", "缺勤",
								isWorkDay, y, m, uid);
						arr.add(clockInForDetails);
					} else {
						ClockInForDetails clockInForDetails = new ClockInForDetails(nowdate, "无", "无", "无", "无",
								isWorkDay, y, m, uid);
						arr.add(clockInForDetails);
					}

				}
			}
			ExcelData data = new ExcelData();
			String dataName = y + "-" + m + user.getuName() + "考勤统计详情";
			data.setName(dataName);
			List<String> titles = new ArrayList();
			titles.add("日期");
			titles.add("上班打卡时间");
			titles.add("上班打卡状态");
			titles.add("下班时间");
			titles.add("下班打卡状态");
			titles.add("是否是工作日");
			data.setTitles(titles);
			List<List<Object>> rows = new ArrayList();
			List<Object> row = null;
			for (ClockInForDetails re : arr) {
				row = new ArrayList();
				row.add(re.getDate());
				row.add(re.getTimeToClockIn());
				row.add(re.getClockInStatus());
				row.add(re.getTimeToPunchOut());
				row.add(re.getToPunchOutStatus());
				if (re.getIsWorkDay().equals("y")) {
					row.add("是");
				} else if (re.getIsWorkDay().equals("n")) {
					row.add("否");
				}
				rows.add(row);
			}
			data.setRows(rows);
			String fileName = dataName + ".xls";
			ExcelUtils.exportExcel(response, fileName, data);
		}
	}

	/**
	 * 个人通行记录查询
	 * 
	 * @param page
	 * @param session
	 * @return
	 */
	@RequestMapping("/MyTravelRecord/{page}")
	public @ResponseBody SimpleResult MyTravelRecord(@PathVariable("page") int page, HttpSession session) {
		Fuser user = (Fuser) session.getAttribute("user");
		List<TravelRecords> arr = TravelRecordsService.geTravelRecordsByUid(user.getuId());
		int size = arr.size();
		int pageindex = 0;
		int pagemax;
		if (size % 30 == 0) {
			pagemax = size / 30;
		} else {
			pagemax = size / 30 + 1;
		}
		if (page > 1)
			pageindex = (page - 1) * 30;
		pageselect pageselect = new pageselect(pageindex, 30, null, user.getuId());
		List<TravelRecords> pagearr = TravelRecordsService.geTravelRecordsPageByUid(pageselect);
		return new SimpleResult(pagearr, pagemax);
	}

	/**
	 * 根据用户名分页模糊查询通行记录
	 * 
	 * @param uName
	 * @param session
	 * @return
	 */
	@RequestMapping("/geTravelRecordsLikeUname/{uName}/{page}")
	public @ResponseBody SimpleResult geTravelRecordsLikeUname(@PathVariable("uName") String uName, HttpSession session,
			@PathVariable("page") int page) {
		Fuser user = (Fuser) session.getAttribute("user");
		Fuser fuser = new Fuser();
		fuser.setcId(user.getcId());
		fuser.setuName(uName);
		List<Fuser> fusersBycIdAndLikeuName = fuserService.getFusersBycIdAndLikeuName(fuser);
		List<TravelRecords> arr = new ArrayList<TravelRecords>();
		for (Fuser userarr : fusersBycIdAndLikeuName) {
			List<TravelRecords> geTravelRecordsByUid = TravelRecordsService.geTravelRecordsByUid(userarr.getuId());
			for (TravelRecords travelRecords : geTravelRecordsByUid) {
				arr.add(travelRecords);
			}
		}
		int size = arr.size();
		int pageindex = 0;
		int pagemax;
		if (size % 30 == 0) {
			pagemax = size / 30;
		} else {
			pagemax = size / 30 + 1;
		}
		if (page > 1)
			pageindex = (page - 1) * 30;
		int count = 0;
		List<travelRecordsBean> beans = new ArrayList<travelRecordsBean>();
		for (int i = 0; i < arr.size(); i++) {
			if (i == pageindex || i > pageindex) {
				if (count < 30) {
					TravelRecords travelRecords = arr.get(i);
					Integer getuId = travelRecords.getuId();
					Fuser fuserByuId = fuserService.getFuserByuId(getuId);
					Equipment equipmentBySn = equipmentService.getEquipmentBySn(travelRecords.geteSn());
					beans.add(new travelRecordsBean(travelRecords.gettId(), travelRecords.gettTime(),
							fuserByuId.getuName(), travelRecords.getcId(), travelRecords.getStrangerImg(),
							fuserByuId.getuImg(), equipmentBySn.geteName()));
					count++;
				}
			}
		}

		return new SimpleResult(beans, pagemax);

	}

	/**
	 * 根据时间段分页查询通行记录
	 * 
	 * @param begin
	 * @param end
	 * @param page
	 * @param session
	 * @return
	 */
	@RequestMapping("/geTravelRecordsbytimequantum/{begin}/{end}/{page}")
	public @ResponseBody SimpleResult geTravelRecordsbytimequantum(@PathVariable("begin") String begin,
			@PathVariable("end") String end, @PathVariable("page") int page, HttpSession session) {
		Fuser user = (Fuser) session.getAttribute("user");
		timePeriodQuery getall = new timePeriodQuery(begin, end, user.getcId(), null, null);
		List<TravelRecords> geTravelRecordsByTimePeriod = TravelRecordsService.geTravelRecordsByTimePeriod(getall);
		int size = geTravelRecordsByTimePeriod.size();
		int pageindex = 0;
		int pagemax;
		if (size % 30 == 0) {
			pagemax = size / 30;
		} else {
			pagemax = size / 30 + 1;
		}
		if (page > 1)
			pageindex = (page - 1) * 30;
		timePeriodQuery query = new timePeriodQuery(begin, end, user.getcId(), pageindex, 30);
		List<TravelRecords> geTravelRecordsByTimePeriodPage = TravelRecordsService
				.geTravelRecordsByTimePeriodPage(query);
		List<travelRecordsBean> beans = new ArrayList<travelRecordsBean>();
		for (TravelRecords t : geTravelRecordsByTimePeriodPage) {
			Fuser fuserByuId = fuserService.getFuserByuId(t.getuId());
			Equipment equipmentBySn = equipmentService.getEquipmentBySn(t.geteSn());
			beans.add(new travelRecordsBean(t.gettId(), t.gettTime(), fuserByuId.getuName(), t.getcId(),
					t.getStrangerImg(), fuserByuId.getuImg(), equipmentBySn.geteName()));
		}
		return new SimpleResult(beans, pagemax);
	}

	/**
	 * 根据设备名称模糊查询陌生记录
	 * 
	 * @param eName
	 * @param session
	 * @return
	 */
	@RequestMapping("/getstrangerRecordslikeeName/{eName}/{page}")
	public @ResponseBody SimpleResult getstrangerRecordslikeeName(@PathVariable("eName") String eName,
			@PathVariable("page") Integer page, HttpSession session) {
		Fuser user = (Fuser) session.getAttribute("user");
		Equipment equipment = new Equipment();
		equipment.setcId(user.getcId());
		equipment.seteName(eName);
		int pagemax = 0;
		List<TravelRecords> arr = new ArrayList<TravelRecords>();
		List<Equipment> equipmentsByCidAndLikeeName = equipmentService.getEquipmentsByCidAndLikeeName(equipment);
		for (Equipment eq : equipmentsByCidAndLikeeName) {
			List<TravelRecords> getstrangerRecordslikeeName = TravelRecordsService
					.getstrangerRecordslikeeName(eq.getsN());
			for (TravelRecords re : getstrangerRecordslikeeName) {
				arr.add(re);
			}
		}
		List<TravelRecords> newarr = new ArrayList<TravelRecords>();
		int size = arr.size();

		int pageindex = 0;
		if (size % 30 == 0) {
			pagemax = size / 20;
		} else {
			pagemax = size / 20 + 1;
		}
		if (page > 1)
			pageindex = (page - 1) * 20;
		int count = 0;
		for (int i = 0; i < arr.size(); i++) {
			if (i == pageindex || i > pageindex) {
				if (count < 20) {
					newarr.add(arr.get(i));
					count++;
				}
			}
		}
		List<travelRecordsBean> recordsBeans = new ArrayList<travelRecordsBean>();
		for (TravelRecords travelRecords : newarr) {
			String strangerImg = travelRecords.getStrangerImg();
			String eSn = travelRecords.geteSn();
			Integer tId = travelRecords.gettId();
			Equipment equipmentBySn = equipmentService.getEquipmentBySn(eSn);
			String tTime = travelRecords.gettTime();
			recordsBeans
					.add(new travelRecordsBean(tId, tTime, null, null, strangerImg, null, equipmentBySn.geteName()));
		}
		return new SimpleResult(recordsBeans, pagemax);
	}

	@RequestMapping("/getstrangerRecordslbytimequantum/{begin}/{end}/{page}")
	public @ResponseBody SimpleResult getstrangerRecordslbytimequantum(@PathVariable("begin") String begin,
			@PathVariable("end") String end, @PathVariable("page") int page, HttpSession session)
			throws ParseException {
		Fuser user = (Fuser) session.getAttribute("user");
		Company companyByCid = companyService.getCompanyByCid(user.getcId());
		List<TravelRecords> allstrangerRecords = new ArrayList<TravelRecords>();
		String geteSn = companyByCid.geteSn();
		begin += " 00:00:00";
		end += " 00:00:00";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date begintiem = sdf.parse(begin);
		Date endtiem = sdf.parse(end);
		int pagemax = 0;
		if (geteSn != null && !geteSn.equals("")) {
			if (geteSn.indexOf("-") != -1) {
				String[] st = geteSn.split("-");
				List<String> strarr = new ArrayList<String>();
				for (String s : st) {
					strarr.add(s);
				}

				List<TravelRecords> lodarr = TravelRecordsService.getAllstrangerRecords(strarr);
				List<TravelRecords> arr = new ArrayList<TravelRecords>();
				for (TravelRecords t : lodarr) {
					Date ttime = sdf.parse(t.gettTime());
					if (ttime.before(endtiem) && ttime.after(begintiem)) {
						arr.add(t);
					}
				}
				int size = arr.size();

				int pageindex = 0;
				if (size % 30 == 0) {
					pagemax = size / 30;
				} else {
					pagemax = size / 30 + 1;
				}
				if (page > 1)
					pageindex = (page - 1) * 30;
				int count = 0;
				for (int i = 0; i < arr.size(); i++) {
					if (i == pageindex || i > pageindex) {
						if (count < 30) {
							allstrangerRecords.add(arr.get(i));
							count++;
						}
					}
				}
			} else {
				List<String> strarr = new ArrayList<String>();
				strarr.add(geteSn);
				List<TravelRecords> arr = TravelRecordsService.getAllstrangerRecords(strarr);
				int size = arr.size();

				int pageindex = 0;
				if (size % 30 == 0) {
					pagemax = size / 30;
				} else {
					pagemax = size / 30 + 1;
				}
				if (page > 1)
					pageindex = (page - 1) * 30;
				int count = 0;
				for (int i = 0; i < arr.size(); i++) {
					if (i == pageindex || i > pageindex) {
						if (count < 30) {
							allstrangerRecords.add(arr.get(i));
							count++;
						}
					}
				}
			}

		}

		List<travelRecordsBean> recordsBeans = new ArrayList<travelRecordsBean>();
		for (TravelRecords travelRecords : allstrangerRecords) {
			String strangerImg = travelRecords.getStrangerImg();
			String eSn = travelRecords.geteSn();
			Integer tId = travelRecords.gettId();
			Equipment equipmentBySn = equipmentService.getEquipmentBySn(eSn);
			String tTime = travelRecords.gettTime();
			recordsBeans
					.add(new travelRecordsBean(tId, tTime, null, null, strangerImg, null, equipmentBySn.geteName()));
		}
		return new SimpleResult(recordsBeans, pagemax);
	}
}
